<template>
  <div :class="{'hidden':hidden}" class="pagination-container">
    <el-pagination :background="background" :current-page.sync="currentPage" :page-size.sync="pageSize" :layout="layout" :page-sizes="pageSizes" :total="total" v-bind="$attrs" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
</template>

<script>
import { scrollTo } from '@/utils/scroll-to'

export default {
  name: 'ApePagination',
  props: {
    total: {
      required: true,
      type: Number
    },
    skipCount: {
      type: Number,
      default: 0
    },
    maxResultCount: {
      type: Number,
      default: 10
    },

    background: {
      type: Boolean,
      default: true
    },
    layout: {
      type: String,
      default: 'total, sizes, prev, pager, next, jumper'
    },
    autoScroll: {
      type: Boolean,
      default: true
    },
    hidden: {
      type: Boolean,
      default: false
    },
    pageSizes: {
      type: Array,
      default() {
        const result = [10, 20, 30, 50];
        if (result.indexOf(this.maxResultCount) === -1) {
          result.unshift(this.maxResultCount);
        }
        return result;
      }
    }
  },
  computed: {
    currentPage: {
      get() {
        return parseInt((this.skipCount / this.maxResultCount) + 1)
      },
      set(val) {
        this.$emit('update:skipCount', (val - 1) * this.maxResultCount + (this.skipCount % this.maxResultCount))
      }
    },
    pageSize: {
      get() {
        return this.maxResultCount
      },
      set(val) {
        this.$emit('update:maxResultCount', val)
      }
    }
  },
  methods: {
    handleSizeChange(val) {
      this.$emit('update:skipCount', 0) // 切换每页显示数量时，重置当前页为第一页
      this.$emit('pagination', { skipCount: 0, maxResultCount: val })
      if (this.autoScroll) {
        scrollTo(0, 800)
      }
    },
    handleCurrentChange(val) {
      this.$emit('pagination', { skipCount: val, maxResultCount: this.pageSize })
      if (this.autoScroll) {
        scrollTo(0, 800)
      }
    }
  }
}
</script>

<style scoped>
/* .pagination-container {
  background: #fff;
  padding: 32px 16px;
} */
.pagination-container.hidden {
  display: none;
}
</style>
